package com.zytech.zspider.client;

import com.zytech.zspider.client.eventlistener.TaskEventListener;
import com.zytech.zspider.eventbus.EventBus;
import com.zytech.zspider.eventbus.EventListener;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;

/**
 * @author siuming
 */
public class ClientBootstrap {

    public static void main(String[] args) throws IOException {

        Properties props = PropertiesLoaderUtils.loadProperties(new ClassPathResource("/application.properties"));
        String listenQueueName = props.getProperty("listen.queue.name", "task:assemble:queue");

        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("/application-context.xml");
        listenOnQueue(listenQueueName, context);
        listenOnUnlessShuttingdown(context);
    }

    private static void listenOnQueue(String listenQueueName, ClassPathXmlApplicationContext context) {
        EventBus eventBus = context.getBean(EventBus.class);
        EventListener eventListener = context.getBean(TaskEventListener.class);
        eventBus.consumeQueue(listenQueueName, eventListener);
    }

    private static void listenOnUnlessShuttingdown(final ClassPathXmlApplicationContext context) {
        final CountDownLatch keepAlive = new CountDownLatch(1);
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                keepAlive.countDown();
                if (null != context) {
                    context.close();
                }
            }
        });

        Thread keepAliveThread = new Thread() {
            @Override
            public void run() {
                try {
                    keepAlive.await();
                } catch (InterruptedException ignore) {
                    Thread.currentThread().interrupt();
                }
            }
        };

        keepAliveThread.start();
    }
}
